package com.hedl.practice.diyJava.gather.study_equals;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Study_list_equals {
    public static void main(String[] args) {

        List<String> list = Arrays.asList("A","B","C","D");
        System.out.println(list.contains(new String("C")));
        System.out.println(list.indexOf(new String("C")));


        List<Person> people = Arrays.asList(new Person("小明"),new Person("小红"),new Person("Bob"));
        System.out.println(people.contains(new Person(null)));
    }
}

class Person{
    String name;
    int age;

    public Person(String name) {
        this.name = name;
        //this.age = age;
    }

    //如果this.name为null，那么equals()方法会报错  NullPointerException
    /*public boolean equals(Object o){
        if (o instanceof Person){
            Person p = (Person) o;
            return this.name.equals(p.name) && this.age == p.age;
        }
        return false;
    }*/

    //改进
    /*public boolean equals(Object o){
        if (o instanceof Person){
            Person p = (Person) o;
            boolean nameEquals = false;     //定义了原始的判断
            if (this.name == null && p.name == null){       //先调用本地name判断是否等于空，不等于就全部都不等于
                nameEquals = true;
            }
            if (this.name != null){     //调用本地name判断是否不等于空
                nameEquals = this.name.equals(p.name);      //调用本地name和传入的name做比较，改变nameEquals的判断
            }
            return nameEquals && this.age == p.age;     //在做age判断
        }
        return false;
    }*/

    //改进，上面的代码太多，太复杂了
    public boolean equals(Object o){
        if (o instanceof Person){
            Person p = (Person) o;
            return Objects.equals(this.name,p.name) && this.age == p.age;
        }
        return false;
    }


}
